package com.slz3.business.task;

import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.util.ConvertUtil;
import com.slz3.business.frame.util.ConverterUtils;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.memberManagement.drawTicket.domain.DrawTicketAppVo;
import com.slz3.business.module.memberManagement.drawTicket.domain.DrawTicketConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @FileName: TaskTimer
 * @Description: 定时器任务
 */

@Slf4j
@Component
public class DrawTicketTaskTimer {



    /**
     * @Description：优惠券同步 每天晚上1点执行
     */
    @Scheduled(cron = "0 30 0 1/1 * ?")
    private void sysncDrawTicket(){
        log.info("定时任务优惠券是否过期同步开始");
        // 循环优惠券
        String key = String.format("%s:%s", RK.SERVICE, RK.DRAW_TICKET).concat("*");
        Set<String> keys = Jedis.db0.kes(key);
        Date date = new Date();
        long endTime = date.getTime() / 1000l;
        for (String drawTickKey: keys) {
            // 查询优惠券
            List userDraTicketList = Jedis.db0.getListStartEnd(ConverterUtils.toString(drawTickKey), 0, -1);
            List<DrawTicketAppVo> drawTicketAppVos = ConvertUtil.objToList(userDraTicketList, DrawTicketAppVo.class);
            for (DrawTicketAppVo vo: drawTicketAppVos ) {
                String expireDay = vo.getExpireDay();
                // 比较时间
                if(VE.isNotEmpty(expireDay)){
                    Long expire = ConverterUtils.toLong(expireDay);
                    // 查看优惠券是否失效
                    if(expire < endTime){
                        // 增加历史抽奖券
                        Map resultMap = ConvertUtil.objToMap(Jedis.db0.rightPop(drawTickKey));
                        // 获取出用户ID
                        String userId = vo.getUserId();
                        log.info("用户：" + userId + "的用户优惠券：" + vo.getId() + "过期");
                        // 增加历史抽奖券
                        String historyKey = String.format("%s:%s:%s", RK.SERVICE, RK.HISTORY_DRAW_TICKET_LIST, userId);
                        if (resultMap != null) {
                            vo.setStatus(DrawTicketConstants.OVER_DUE);// 已经使用
                            Map result = ConvertUtil.objToMap(vo);
                            Jedis.db0.lpush(historyKey, result);
                        }
                    }
                }
            }
            log.info("定时任务优惠券是否过期同步结束");
        }
    }





}